<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="词典名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入词典名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="语言分类" prop="languageCategory">
        <el-select
          v-model="queryParams.languageCategory"
          placeholder="语言分类"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="lang in languageOptions"
            :key="lang.id"
            :label="lang.name"
            :value="lang.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-input
          v-model="queryParams.category"
          placeholder="请输入分类"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="词典类型" prop="isFree">
        <el-select
          v-model="queryParams.isFree"
          placeholder="请选择类型"
          clearable
          style="width: 240px"
        >
          <el-option label="免费" value="1" />
          <el-option label="VIP" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['module:dict:book:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['module:dict:book:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['module:dict:book:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bookList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="词典ID" align="center" prop="id" width="200" />
      <el-table-column label="词典名称" align="center" prop="name" :show-overflow-tooltip="true" />
      <el-table-column label="描述" align="center" prop="description" :show-overflow-tooltip="true" />
      <el-table-column label="分类" align="center" prop="category" />
      <el-table-column label="语言分类" align="center" prop="languageCategory" />
      <el-table-column label="词汇数量" align="center" prop="length" />
      <el-table-column label="类型" align="center" prop="isFree" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isFree === '1'" type="success" size="small">免费</el-tag>
          <el-tag v-else type="warning" size="small">VIP</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="标签" align="center" prop="tags">
        <template slot-scope="scope">
          <el-tag
            v-for="tag in scope.row.tags"
            :key="tag"
            style="margin-right: 5px;"
          >{{ tag }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240">
        <template slot-scope="scope">
        <el-button
          size="mini"
          type="text"
          icon="el-icon-edit"
          @click="handleEditWords(scope.row)"
          v-hasPermi="['module:dict:book:query']"
        >编辑词典</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['module:dict:book:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['module:dict:book:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改词典对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="词典ID" prop="id">
          <el-input v-model="form.id" placeholder="请输入词典ID或上传JSON自动生成" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="词典名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入词典名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-input v-model="form.category" placeholder="请输入分类（如：考试词汇、日常用语等）" />
        </el-form-item>
        <el-form-item label="词汇数量" prop="length" v-if="isEdit">
          <el-input-number v-model="form.length" controls-position="right" :min="0" disabled />
        </el-form-item>
        <el-form-item label="语言分类" prop="languageCategory">
          <el-select v-model="form.languageCategory" placeholder="请选择语言分类" style="width: 100%">
            <el-option
              v-for="lang in languageOptions"
              :key="lang.id"
              :label="lang.name"
              :value="lang.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否免费" prop="isFree">
          <el-radio-group v-model="form.isFree">
            <el-radio label="1">免费</el-radio>
            <el-radio label="0">VIP</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-select
            v-model="form.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择或输入标签"
            style="width: 100%"
          >
            <el-option
              v-for="tag in tagOptions"
              :key="tag.name"
              :label="tag.name"
              :value="tag.name"
            />
          </el-select>
        </el-form-item>
        
        <!-- 单词数据文件上传 -->
        <el-form-item label="单词数据文件" v-if="!isEdit">
          <el-upload
            ref="wordFileUpload"
            class="word-file-upload"
            drag
            :limit="1"
            accept=".json,.doc,.docx"
            :auto-upload="false"
            :on-change="handleWordFileChange"
            :on-remove="handleWordFileRemove"
            :file-list="wordFileList"
            action="#"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将单词数据文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              <p style="margin: 5px 0; color: #606266;">
                <i class="el-icon-info"></i> 支持格式：JSON、Word文档（.doc/.docx）
              </p>
              <p style="margin: 5px 0; color: #909399; font-size: 12px;">
                • JSON格式：支持英语、日语、德语等多种格式<br/>
                • Word格式：每行一个单词，格式为"单词 | 翻译"<br/>
                • 上传后将自动解析并导入单词数据到数据库
              </p>
            </div>
          </el-upload>
          
          <!-- 文件解析状态 -->
          <div v-if="uploadStatus.show" style="margin-top: 10px;">
            <el-alert
              :title="uploadStatus.title"
              :type="uploadStatus.type"
              :closable="false"
              show-icon
            >
              <div v-if="uploadStatus.details">
                <p v-for="(detail, index) in uploadStatus.details" :key="index" style="margin: 5px 0;">
                  {{ detail }}
                </p>
              </div>
            </el-alert>
          </div>
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 编辑词典单词对话框 -->
    <el-dialog 
      :title="editWordsTitle" 
      :visible.sync="editWordsOpen" 
      width="90%" 
      append-to-body
      :close-on-click-modal="false"
      @close="handleEditWordsClose"
    >
      <div style="margin-bottom: 15px;">
        <el-input
          v-model="wordSearchText"
          placeholder="搜索单词或翻译"
          prefix-icon="el-icon-search"
          clearable
          style="width: 300px;"
          @input="handleWordSearch"
        />
        <span style="margin-left: 20px; color: #909399;">
          共 {{ filteredWordList.length }} 个单词
        </span>
      </div>
      
      <el-table 
        v-loading="wordLoading" 
        :data="paginatedWordList" 
        border
        max-height="500"
      >
        <el-table-column label="单词" align="center" prop="word" width="150" :show-overflow-tooltip="true" />
        <el-table-column label="标注" align="center" prop="notation" width="150" :show-overflow-tooltip="true" v-if="hasNotation" />
        <el-table-column label="翻译" align="center" prop="translation" :show-overflow-tooltip="true" min-width="250" />
        <el-table-column label="美式音标" align="center" prop="phoneticUs" width="130" :show-overflow-tooltip="true" />
        <el-table-column label="英式音标" align="center" prop="phoneticUk" width="130" :show-overflow-tooltip="true" />
        <el-table-column label="操作" align="center" width="120" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleEditWord(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeleteWord(scope.row)"
              style="color: #F56C6C;"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="wordTotal > 0"
        :total="wordTotal"
        :page.sync="wordQueryParams.pageNum"
        :limit.sync="wordQueryParams.pageSize"
        @pagination="handleWordPagination"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="editWordsOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 编辑单词对话框 -->
    <el-dialog 
      :title="editWordTitle" 
      :visible.sync="editWordOpen" 
      width="600px" 
      append-to-body
    >
      <el-form ref="wordForm" :model="wordForm" :rules="wordRules" label-width="100px">
        <el-form-item label="单词" prop="word">
          <el-input v-model="wordForm.word" placeholder="请输入单词" />
        </el-form-item>
        <el-form-item label="标注" prop="notation" v-if="hasNotation">
          <el-input v-model="wordForm.notation" placeholder="请输入标注（如日语假名）" />
        </el-form-item>
        <el-form-item label="翻译" prop="translation">
          <el-input v-model="wordForm.translation" type="textarea" :rows="3" placeholder="请输入翻译（多个翻译用分号分隔）" />
        </el-form-item>
        <el-form-item label="美式音标" prop="phoneticUs">
          <el-input v-model="wordForm.phoneticUs" placeholder="请输入美式音标" />
        </el-form-item>
        <el-form-item label="英式音标" prop="phoneticUk">
          <el-input v-model="wordForm.phoneticUk" placeholder="请输入英式音标" />
        </el-form-item>
        <el-form-item label="例句" prop="exampleSentence">
          <el-input v-model="wordForm.exampleSentence" type="textarea" :rows="2" placeholder="请输入例句" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitWordForm">确 定</el-button>
        <el-button @click="editWordOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDictBook, getDictBook, delDictBook, addDictBook, updateDictBook } from "@/api/module/dict";
import { getAllLanguageCategory } from "@/api/module/dict";
import { getAllDictTag } from "@/api/module/dict";
import { getToken } from "@/utils/auth";

export default {
  name: "DictBook",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 词典表格数据
      bookList: [],
      // 语言分类选项
      languageOptions: [],
      // 标签选项
      tagOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否是编辑模式
      isEdit: false,
      // 单词数据文件列表
      wordFileList: [],
      // 上传状态
      uploadStatus: {
        show: false,
        title: '',
        type: 'info',
        details: []
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        languageCategory: undefined,
        category: undefined,
        isFree: undefined
      },
      // 编辑词典单词相关
      editWordsOpen: false,
      editWordsTitle: "",
      currentBookId: "",
      wordLoading: false,
      wordList: [],
      filteredWordList: [],
      wordSearchText: "",
      wordTotal: 0,
      wordQueryParams: {
        pageNum: 1,
        pageSize: 20
      },
      hasNotation: false,
      // 编辑单个单词
      editWordOpen: false,
      editWordTitle: "",
      wordForm: {},
      wordRules: {
        word: [
          { required: true, message: "单词不能为空", trigger: "blur" }
        ],
        translation: [
          { required: true, message: "翻译不能为空", trigger: "blur" }
        ]
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: "词典ID不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "词典名称不能为空", trigger: "blur" }
        ],
        url: [
          { required: true, message: "文件路径不能为空", trigger: "blur" }
        ],
        languageCategory: [
          { required: true, message: "语言分类不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getLanguageOptions();
    this.getTagOptions();
  },
  methods: {
    /** 查询词典列表 */
    getList() {
      this.loading = true;
      listDictBook(this.queryParams).then(response => {
        this.bookList = response.rows.map(item => {
          // 确保isFree是字符串类型，以便正确显示
          // 确保tags是数组类型
          return {
            ...item,
            isFree: item.isFree !== undefined && item.isFree !== null ? String(item.isFree) : '1',
            tags: Array.isArray(item.tags) ? item.tags : []
          };
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取语言分类选项 */
    getLanguageOptions() {
      getAllLanguageCategory().then(response => {
        this.languageOptions = response.data;
      });
    },
    /** 获取标签选项 */
    getTagOptions() {
      getAllDictTag().then(response => {
        this.tagOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        description: undefined,
        category: undefined,
        url: undefined,
        length: 0,
        language: undefined,
        languageCategory: undefined,
        status: "0",
        isFree: "1",
        tags: [],
        remark: undefined
      };
      this.isEdit = false;
      this.wordFileList = [];
      this.uploadStatus = {
        show: false,
        title: '',
        type: 'info',
        details: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isEdit = false;
      this.open = true;
      this.title = "添加词典";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isEdit = true;
      const id = row.id || this.ids[0]
      getDictBook(id).then(response => {
        this.form = response.data;
        // 确保isFree是字符串类型，以便单选框正确选中
        if (this.form.isFree !== undefined && this.form.isFree !== null) {
          this.form.isFree = String(this.form.isFree);
        }
        // 确保tags是数组类型，避免undefined导致indexOf错误
        if (!Array.isArray(this.form.tags)) {
          this.form.tags = [];
        }
        this.open = true;
        this.title = "修改词典";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.isEdit) {
            updateDictBook(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 检查是否有文件上传
            if (this.wordFileList.length > 0) {
              // 有文件上传，使用新的导入API
              this.uploadDictWithFile();
            } else {
              // 没有文件，使用普通添加
              addDictBook(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        }
      });
    },
    /** 上传词典文件并导入 */
    uploadDictWithFile() {
      const loading = this.$loading({
        lock: true,
        text: '正在上传并导入词典数据，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 创建FormData
      const formData = new FormData();
      
      // 添加文件
      const file = this.wordFileList[0].raw;
      formData.append('file', file);
      
      // 添加词典信息
      formData.append('dictBook', JSON.stringify(this.form));
      
      // 调用导入API
      import("@/api/module/dict").then(module => {
        module.importDictBook(formData).then(response => {
          loading.close();
          this.$modal.msgSuccess(response.msg || '词典导入成功');
          this.open = false;
          this.getList();
        }).catch(error => {
          loading.close();
          console.error('导入失败：', error);
          this.$modal.msgError('词典导入失败：' + (error.msg || error.message || '未知错误'));
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除词典编号为"' + ids + '"的数据项？').then(function() {
        return delDictBook(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 处理单词文件上传 */
    handleWordFileChange(file, fileList) {
      this.wordFileList = fileList;
      const uploadFile = file.raw;
      const fileName = uploadFile.name;
      const fileType = fileName.substring(fileName.lastIndexOf('.')).toLowerCase();
      
      // 重置上传状态
      this.uploadStatus = {
        show: true,
        title: '正在解析文件...',
        type: 'info',
        details: [`文件名：${fileName}`, `文件大小：${(uploadFile.size / 1024).toFixed(2)} KB`]
      };
      
      if (fileType === '.json') {
        // 处理JSON文件
        const reader = new FileReader();
        reader.onload = (e) => {
          try {
            const jsonData = JSON.parse(e.target.result);
            if (!Array.isArray(jsonData)) {
              throw new Error('JSON格式错误：必须是数组格式');
            }
            
            // 分析JSON格式
            const wordCount = jsonData.length;
            let hasNotation = false;
            let hasUsphone = false;
            let hasUkphone = false;
            
            if (jsonData.length > 0) {
              const sample = jsonData[0];
              hasNotation = !!sample.notation;
              hasUsphone = !!sample.usphone;
              hasUkphone = !!sample.ukphone;
            }
            
            // 判断语言类型
            let language = 'en';
            let languageCategory = 'en';
            if (hasNotation) {
              language = 'romaji';
              languageCategory = 'ja';
            }
            
            // 自动填充表单
            const dictId = fileName.replace(/\.(json|JSON)$/, '');
            this.form.id = dictId;
            this.form.name = dictId;
            this.form.description = `从${fileName}导入`;
            this.form.category = hasNotation ? '日语学习' : (fileName.includes('german') || fileName.includes('deutsch') ? '德语学习' : '自定义');
            this.form.url = `/dicts/${fileName}`;
            this.form.length = wordCount;
            this.form.language = language;
            this.form.languageCategory = languageCategory;
            this.form.tags = ['自定义导入'];
            this.form.remark = `从 ${fileName} 导入，共 ${wordCount} 个单词`;
            
            // 更新上传状态
            this.uploadStatus = {
              show: true,
              title: '✓ JSON文件解析成功',
              type: 'success',
              details: [
                `✓ 检测到 ${wordCount} 个单词`,
                `✓ 语言类型：${hasNotation ? '日语' : (fileName.includes('german') ? '德语' : '英语')}`,
                hasNotation ? '✓ 包含假名标注(notation)' : '',
                hasUsphone ? '✓ 包含美式音标' : '',
                hasUkphone ? '✓ 包含英式音标' : '',
                '提示：点击"确定"保存词典信息并自动导入单词数据'
              ].filter(Boolean)
            };
          } catch (error) {
            this.uploadStatus = {
              show: true,
              title: '✗ JSON文件解析失败',
              type: 'error',
              details: [error.message]
            };
            this.wordFileList = [];
          }
        };
        reader.readAsText(uploadFile);
      } else if (fileType === '.doc' || fileType === '.docx') {
        // Word文件需要后端处理
        this.uploadStatus = {
          show: true,
          title: 'Word文件已选择',
          type: 'warning',
          details: [
            '✓ Word文件已准备就绪',
            '提示：请填写基本信息后点击"确定"',
            '系统将自动解析Word文档并导入单词数据'
          ]
        };
        
        // 自动填充部分表单
        const dictId = fileName.replace(/\.(doc|docx|DOC|DOCX)$/, '');
        this.form.id = dictId;
        this.form.name = dictId;
        this.form.description = `从${fileName}导入`;
        this.form.category = '自定义';
        this.form.url = `/dicts/${dictId}.json`;
        this.form.language = 'en';
        this.form.languageCategory = 'en';
        this.form.tags = ['自定义导入'];
      }
    },
    /** 移除上传的文件 */
    handleWordFileRemove(file, fileList) {
      this.wordFileList = [];
      this.uploadStatus = {
        show: false,
        title: '',
        type: 'info',
        details: []
      };
    },
    /** 编辑词典单词 */
    handleEditWords(row) {
      this.editWordsTitle = `${row.name} - 编辑词汇`;
      this.editWordsOpen = true;
      this.currentBookId = row.id;
      this.wordLoading = true;
      this.wordSearchText = "";
      this.wordQueryParams.pageNum = 1;
      
      // 导入API
      import("@/api/module/dict").then(module => {
        // 调用获取词典单词列表的API
        module.listDictWordByBookId(row.id).then(response => {
          this.wordList = response.rows || response.data || [];
          this.filteredWordList = this.wordList;
          this.wordTotal = this.filteredWordList.length;
          
          // 检查是否有notation字段（日语等语言）
          this.hasNotation = this.wordList.some(word => word.notation && word.notation.trim());
          
          this.wordLoading = false;
        }).catch(() => {
          this.$modal.msgError("获取词典单词列表失败");
          this.wordLoading = false;
          this.wordList = [];
          this.filteredWordList = [];
          this.wordTotal = 0;
        });
      });
    },
    /** 编辑单个单词 */
    handleEditWord(row) {
      this.wordForm = Object.assign({}, row);
      this.editWordTitle = "编辑单词";
      this.editWordOpen = true;
    },
    /** 删除单个单词 */
    handleDeleteWord(row) {
      this.$modal.confirm('是否确认删除单词「' + row.word + '」？').then(() => {
        // 导入API
        import("@/api/module/dict").then(module => {
          module.deleteWord(row.id).then(response => {
            this.$modal.msgSuccess("删除成功");
            // 重新加载当前词典的单词列表
            this.handleEditWords({ id: this.currentBookId, name: this.editWordsTitle.replace(' - 编辑词汇', '') });
          }).catch(() => {
            this.$modal.msgError("删除失败");
          });
        });
      }).catch(() => {});
    },
    /** 提交单词表单 */
    submitWordForm() {
      this.$refs["wordForm"].validate(valid => {
        if (valid) {
          // 导入API
          import("@/api/module/dict").then(module => {
            module.updateWord(this.wordForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.editWordOpen = false;
              // 更新列表中的数据
              const index = this.wordList.findIndex(w => w.id === this.wordForm.id);
              if (index !== -1) {
                this.$set(this.wordList, index, Object.assign({}, this.wordForm));
                this.handleWordSearch(); // 重新过滤
              }
            }).catch(() => {
              this.$modal.msgError("修改失败");
            });
          });
        }
      });
    },
    /** 单词搜索 */
    handleWordSearch() {
      if (!this.wordSearchText || this.wordSearchText.trim() === "") {
        this.filteredWordList = this.wordList;
      } else {
        const searchText = this.wordSearchText.toLowerCase();
        this.filteredWordList = this.wordList.filter(word => {
          return (word.word && word.word.toLowerCase().includes(searchText)) ||
                 (word.translation && word.translation.toLowerCase().includes(searchText)) ||
                 (word.notation && word.notation.toLowerCase().includes(searchText));
        });
      }
      this.wordTotal = this.filteredWordList.length;
      this.wordQueryParams.pageNum = 1;
    },
    /** 单词列表分页 */
    handleWordPagination() {
      // 分页已通过computed属性处理
    },
    /** 关闭编辑词典对话框时清空数据 */
    handleEditWordsClose() {
      this.wordList = [];
      this.filteredWordList = [];
      this.wordSearchText = "";
      this.wordTotal = 0;
      this.wordQueryParams.pageNum = 1;
      this.wordQueryParams.pageSize = 20;
      this.currentBookId = "";
      this.hasNotation = false;
    }
  },
  computed: {
    /** 分页后的单词列表 */
    paginatedWordList() {
      const start = (this.wordQueryParams.pageNum - 1) * this.wordQueryParams.pageSize;
      const end = start + this.wordQueryParams.pageSize;
      return this.filteredWordList.slice(start, end);
    }
  }
};
</script>

<style scoped>
.word-file-upload {
  width: 100%;
}

.word-file-upload >>> .el-upload {
  width: 100%;
}

.word-file-upload >>> .el-upload-dragger {
  width: 100%;
  height: 180px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.word-file-upload >>> .el-icon-upload {
  font-size: 67px;
  color: #409EFF;
  margin: 0;
  line-height: 1;
}

.word-file-upload >>> .el-upload__text {
  font-size: 14px;
  color: #606266;
  margin-top: 10px;
}

.word-file-upload >>> .el-upload__text em {
  color: #409EFF;
  font-style: normal;
}
</style>

